<template>

<div>
    <el-upload
      :action="uploadAction"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :limit="maxCount"
      >
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

</div>
   
</template>

<script>
  import config from '@/config/config'
export default {
  name: 'multiUpload',
  props:{
    // 图片服务器地址
    uploadAction:{
      type:String,
      required: true
    },
    // 图片数组
    value: Array,
    // 图片的最大上传数量
    maxCount:{
      type:Number,
      default:5
    }

  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false 
    };
  },
  computed:{
    fileList(){  
      const productValue = this.value 
      let fileList = []
      if(productValue){
        for(let i=0;i<productValue.length;i++){
          fileList.push({ url:productValue[i] })
        }
      } 
      return fileList
    }
  },
 
  methods: {
    // 删除
    handleRemove(file, fileList) {
      // console.log(file, fileList); 
      this.fileList = fileList
      this.handleUpload(this.fileList)
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传成功
    handleUploadSuccess(response,file,fileList){
      // console.log(response); console.log(file); console.log(fileList); 
      this.fileList.push({url:config.BASE_URL + response.data.name})
      this.handleUpload(this.fileList);  
    },
    // 超出最大数限制
    handleExceed(){
      this.$message.warning(`最多只能上传${this.maxCount}张图片` )
    },

    // 通知 调用者
    handleUpload(fileList){
      // console.log(fileList);
      let value = [];
      for(let i=0;i<fileList.length;i++){
        value.push(fileList[i].url)
      }
      // 通过自定义事件返回给 调用者
      this.$emit('input',value)
    }
  }
}
</script>
